package com.atguigu.lease.web.admin.interceptor;

import com.atguigu.lease.common.context.LoginUser;
import com.atguigu.lease.common.context.LoginUserContext;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;

import com.atguigu.lease.web.admin.service.SystemUserService;

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author yjf
 * @version 1.0
 * @description: 后台登录--拦截器 ，注意需要添加到处理器WebAdminMvcConfig才能生效
 * @date 2024/9/13 20:01
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private SystemUserService systemUserService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.在请求头中，获取token
        //如果安装_写，记得swagger里改成-
        String accessToken = request.getHeader("access-token");
        if (StringUtils.hasLength(accessToken)){
            throw new LeaseException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        } else {
            //解析token token一旦过期或被篡改。会抛对应的异常
            Claims claims = JwtUtil.parseToken(accessToken);
            //获取用户id
            Long userId = claims.get("userId", long.class);
            //获取用户名
            String username = claims.get("username", String.class);
            //创建一个LoginUser对象， 只有存储userId，和 username
            LoginUser loginUser = new LoginUser(userId, username);
            // 为了整个项目中中当前线程可以在任一环节取出LoginUser，加了个ThreadLocal
            LoginUserContext.setLoginUser(loginUser);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //释放资源removeLoginUser
        LoginUserContext.removeLoginUser();
    }
}
